package pablo.developer;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class NuevoVehiculo extends Activity {
	String matricula="",modelo="",marca="", color="",id="",name="";
	int idUser;
	private static final String URL_BASE = "http://10.0.2.2:8080/PFCServlets/DatosVehiculo";
	boolean encontrado;
	Vehiculo vehiculo;
	EditText etMatricula,etModelo,etMarca,etColor;
	Button btInsertar;
	
public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.nuevovehiculo);
		
		Bundle bundle  = getIntent().getExtras();
		idUser         = bundle.getInt("idUser");
		name         = bundle.getString("name");
		SetUI();
	}

public void SetUI(){
	
	etMatricula = (EditText)findViewById(R.id.matricula);
	etMarca     = (EditText)findViewById(R.id.marca);
	etModelo    = (EditText)findViewById(R.id.modelo);
	etColor     = (EditText)findViewById(R.id.color);
	
	}
public void insertar(View v){
	updateDatos();
	new HTTPServiceClient().execute(URL_BASE);
	}
public void updateDatos(){
	matricula = etMatricula.getText().toString();
    marca     = etMarca.getText().toString();
    modelo    = etModelo.getText().toString();
    color     = etColor.getText().toString();	
	}
private void showResultConversion(Vehiculo result) {
	
	boolean encontrado = result.getEncontrado();
	if (!encontrado){
		Toast toast1 =Toast.makeText(getApplicationContext(),"Vehiculo Introducido por el usuario/a "+ name , Toast.LENGTH_LONG);
        toast1.show();
		Intent mainIntent = new Intent(NuevoVehiculo.this,MenuPrincipal.class);
		Bundle bundle     = new Bundle();
		bundle.putInt("idUser", idUser);
		bundle.putString("name", name);
		mainIntent.putExtras(bundle);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        NuevoVehiculo.this.startActivity(mainIntent);
       
        
	}
	else{
		Intent mainIntent = new Intent(NuevoVehiculo.this,MenuPrincipal.class);
		Bundle bundle     = new Bundle();
		bundle.putInt("idUser", idUser);
		mainIntent.putExtras(bundle);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        NuevoVehiculo.this.startActivity(mainIntent);
        Toast toast1 =Toast.makeText(getApplicationContext(),"El vehiculo ya existe" , Toast.LENGTH_LONG);
	    toast1.show();
        
        
	}
}

public class HTTPServiceClient extends AsyncTask<String, Void, Vehiculo>{
	final ProgressDialog dialog = new ProgressDialog(NuevoVehiculo.this);
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog.setMessage("Conectando con la base de datos de Uvipool...");
	    dialog.show();
	}
	
	
	@Override
	protected Vehiculo doInBackground(String... url) {
		
		Vehiculo result;
		try 
		{
			result = getResult(url[0]);
		} 
		catch (Exception e) 
		{
			result = Vehiculo.getEmpty();
			e.printStackTrace();
		}
		return result;
	}
	
	protected void onPostExecute(Vehiculo result) {
		dialog.dismiss();
		showResultConversion(result);
		super.onPostExecute(result);
		NuevoVehiculo.this.finish();
	}
	
	private Vehiculo getResult(String url) throws ClientProtocolException, IOException, JSONException{
		id = String.valueOf(idUser);
		VehiculoInputs inputs = new VehiculoInputs(matricula,marca,modelo, color,id);
		JSONObject inputsJson = new JSONObject(inputs.getInputMap());
		String jsonString = HttpUtils.urlContentPost(url, "vehiculoInputs", inputsJson.toString());
		Gson gson = new Gson();
		Vehiculo infor = gson.fromJson(jsonString, Vehiculo.class);
		return infor;
		}
	}

}
